#pragma once
#include<string>
#include<iostream>
#include<functional>
#include<pthread.h>
#include"Log.hpp"
using namespace bit;

namespace ThreadMoudle
{
    class Thread
    {
    private:
        static void* ThreadExcute(void* atr)
        {
            Thread* tmp = static_cast<Thread*>(atr);
            tmp->_f(tmp->_name);
            return nullptr;
        }
    public:
        //函数指针类型：返回值为void，参数为空：
        //typedef void(*func_t)();
        using func_t = std::function<void(const std::string)>;

        //构造函数：
        Thread(const std::string& name, func_t f):_name(name), _f(f)
        {
            //std::cout << "create " << _name << " done!" <<std::endl;
            LOG(INFO, "create %s done!", _name.c_str());
        }
        //线程的执行：
        bool Start()
        {
            bool ret;
            //创建线程之后，线程自动执行：
            int n = pthread_create(&_tid, nullptr, ThreadExcute, (void*)this);
            //std::cout << "线程跑起来啦！" << std::endl;
            LOG(INFO, "线程跑起来啦！" , _name.c_str());
            if(n == 0) ret = true;
            else ret = false;
            return ret;
        }
        //线程的等待：
        void Join()
        {
            pthread_join(_tid, nullptr);
            //std::cout << _name << " Joined successfully!" << std::endl;
            LOG(INFO, "%s Joined successfully!", _name.c_str());
        }
    private:
        func_t _f;              //线程要执行的方法。
        std::string _name;      //线程名字
        pthread_t _tid;         //线程id;
    };
} 